import sys

import pygame

from piece import Piece
from settings import *


def main():
    # 初始化 pygame 。启用 pygame 必不可少的一步，在程序开始阶段执行。
    pygame.init()
    # 创建屏幕对象（也即窗口对象）
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))  # 分辨率是1200*900
    pygame.display.set_caption("俄罗斯方块")  # 窗口标题
    # 屏幕背景色
    bg_color = BG_COLOR
    # 生成方块对象
    piece = Piece('S', screen)
    # 游戏主循环
    while True:
        # 监视键盘和鼠标事件
        check_events(piece)

        # 填充屏幕背景色
        screen.fill(bg_color)
        # 绘制网格
        draw_game_area(screen)
        # 绘制方块
        piece.paint()
        # 刷新屏幕
        pygame.display.flip()


def draw_game_area(screen):
    # 绘制横线
    for i in range(21):
        pygame.draw.line(screen, EDGE_COLOR, (GAME_AREA_LEFT, (GAME_AREA_TOP + (i * CELL_WIDTH))),
                         ((GAME_AREA_LEFT + GAME_AREA_WIDTH), (GAME_AREA_TOP + (i * CELL_WIDTH))))
    # 绘制竖线
    for i in range(11):
        pygame.draw.line(screen, EDGE_COLOR, ((GAME_AREA_LEFT + (i * CELL_WIDTH)), GAME_AREA_TOP),
                         ((GAME_AREA_LEFT + (i * CELL_WIDTH)), (GAME_AREA_TOP + GAME_AREA_HEIGHT)))


def check_events(piece):
    """捕捉和处理键盘按键事件"""
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_DOWN:
                piece.move_down()
            elif event.key == pygame.K_UP:
                piece.turn()
            elif event.key == pygame.K_RIGHT:
                piece.move_right()
            elif event.key == pygame.K_LEFT:
                piece.move_left()


if __name__ == '__main__':
    main()
